package com.xpffly.springboot.config.db.druid;

import com.xpffly.springboot.config.db.druid.annotation.DataSourceNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @Author: xpengfei
 * @Date: 2020/12/12 21:19
 * @Description：用于切换数据源， 继承AbstractRoutingDataSource并重写其中的方法determineCurrentLookupKey()，
 * 在该方法中获取当前线程的数据库类型
 */
public class DruidDynamicDataSource extends AbstractRoutingDataSource {

    private static final Logger logger = LoggerFactory.getLogger(DruidDynamicDataSource.class);

    public static ThreadLocal<DataSourceNames> dbThreadLocal = new ThreadLocal<>();

    /**
     * 设置默认数据源，以及数据源集合
     *
     * @param defaultTargetDataSource 默认数据源
     * @param targetDataSources       数据源集合
     */
    public DruidDynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    /**
     * 获取当前数据源
     *
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        logger.info("当前使用的数据源为，db={}",get().getValue());
        return get();
    }

    public static void clear() {
        dbThreadLocal.remove();
    }

    public static void set(DataSourceNames dataSourceNames) {
        dbThreadLocal.set(dataSourceNames);
    }

    public static DataSourceNames get() {
        return null == dbThreadLocal.get() ? DataSourceNames.STOCK_DB : dbThreadLocal.get();
    }

}
